package setup;

import question.ClassifyInfo;
import question.Classify;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Shawn
 * Date: 2009-6-20
 * Time: 22:30:38
 */
public class Setup {

  public static void addSetup(Connection con, List<SetupInfo> list) throws SQLException {
    String sql = "INSERT INTO setup VALUES (NULL, ?, ?)";
    PreparedStatement ps = con.prepareStatement(sql);
    for (SetupInfo info : list) {
      ps.setInt(1, info.getYdID());
      ps.setInt(2, info.getYdValue());
      ps.executeUpdate();
    }
  }

  public static void delSetup(Connection con, int kmID) throws SQLException {
    String ydIds = getYdString(con, kmID);
    if (ydIds.length() == 0) return;
    String sql = "DELETE FROM setup WHERE ydID IN (" + ydIds + ")";
    con.createStatement().executeUpdate(sql);
  }

  public static List<SetupInfo> getSetupList(Connection con, int kmID) throws SQLException {
    ArrayList<SetupInfo> list = new ArrayList<SetupInfo>();
    String ydIds = getYdString(con, kmID);
    if (ydIds.length() == 0) return list;
    String sql = "SELECT * FROM setup WHERE ydID IN (" + ydIds + ")";
    ResultSet rs = con.createStatement().executeQuery(sql);
    while (rs.next()) list.add(rs2Info(rs));
    return list;
  }

  private static String getYdString(Connection con, int kmID) throws SQLException {
    List<ClassifyInfo> dtList = Classify.getChildren(con, kmID);

    String ydIds = "";
    for (ClassifyInfo dtInfo : dtList) {
      List<ClassifyInfo> ydList = Classify.getChildren(con, dtInfo.getCid());
      for (ClassifyInfo ydInfo : ydList) {
        ydIds += (ydIds.length() == 0 ? "" : ",") + ydInfo.getCid();
      }
    }

    return ydIds;
  }

  private static SetupInfo rs2Info(ResultSet rs) throws SQLException {
    SetupInfo info = new SetupInfo();
    info.setSid(rs.getInt("sid"));
    info.setYdID(rs.getInt("ydID"));
    info.setYdValue(rs.getInt("ydValue"));
    return info;
  }
}
